package data;



public class BlockingQueue implements MessageQueue {

  
  private final Message[] queue;
  private int in, size;


  public BlockingQueue(int max) {
    queue = new Message[max];
    in = 0;
    size = 0;
  }

  public boolean isFull() {
    synchronized(this){
    	return size() >= queue.length;
    }
  }

  public void add(Message message) {
    synchronized(this){  

    	while (isFull()){
    		try {
				this.wait();
			} catch (InterruptedException e) {

			}
    	}
    	queue[in] = message;
    	in = (in + 1) % queue.length;
    	++size;

    	this.notifyAll();
    }
  }

  public boolean isEmpty() {
	return size() == 0;
  }

  public Message remove(){
   synchronized(this){

	   while(isEmpty()){
		   try {
			this.wait();
		} catch (InterruptedException e) {
			return null;
		}
	   }

		int out = (in + queue.length - size) % queue.length;
		Message message = queue[out];
		--size;
		
		this.notify();
		return message;
    }
  }

  public int size() {
    synchronized(this){
    	return size;
    }
  }

}
